package com.ruoyi.inspection.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author He Bo
 * @create 2024/7/29 22:53
 */
@Slf4j
public class GrottoConfig {

    private static String ip = "http://42.192.66.95/grotto";

    private static String login = "/login";

    private static String getTimeDate = "/opin/test";

    public static String login() {
        Map<String, Object> map = new HashMap<>(5);
        map.put("password","Sdkmqzq2023");
        map.put("username","admin");
        HttpResponse execute = HttpRequest
                .post(ip + login)
                .charset("UTF-8")
                .body(JSONUtil.toJsonStr(map))
                .contentType("application/json")
                .timeout(5000)
                .execute();
        int status = execute.getStatus();
        if (status != 200) {
            log.error("请求失败 状态码：{}",status);
            return null;
        }
        String body = execute.body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        if (jsonObject.getInt("code").equals(200)) {
            String token = jsonObject.getStr("token");
            return token;
        } else {
            log.error("请求失败");
            return null;
        }
    }

    public static JSONObject getTimeDate() {
        String login = login();
        if (StrUtil.isEmpty(login)) {
            return new JSONObject();
        }
        HttpResponse execute = HttpRequest
                .get(ip + getTimeDate)
                .charset("UTF-8")
                .header("authorization",login)
                .timeout(5000)
                .execute();
        int status = execute.getStatus();
        if (status != 200) {
            log.error("请求失败 状态码：{}",status);
            return new JSONObject();
        }
        String body = execute.body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        return jsonObject;
    }
}
